package com.carey.blog.framework.latke.servlet;

import java.io.File;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.carey.blog.framework.latke.Latkes;

/**
 * Abstract servlet listener.
 * 
 */
public abstract class AbstractServletListener implements
		ServletContextListener, ServletRequestListener, HttpSessionListener {

	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger
			.getLogger(AbstractServletListener.class.getName());
	/**
	 * Web root.
	 */
	private static String webRoot;

	/**
	 * Initializes context, {@linkplain #webRoot web root}, registers json RPC
	 * services and json RPC service serializers.
	 * 
	 * @param servletContextEvent
	 *            servlet context event
	 */
	@Override
	public void contextInitialized(final ServletContextEvent servletContextEvent) {
		Latkes.check();

		Latkes.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);

		final ServletContext servletContext = servletContextEvent
				.getServletContext();
		webRoot = servletContext.getRealPath("") + File.separator;
		final String catalinaBase = System.getProperty("catalina.base");
		LOGGER.log(Level.INFO, "[Web root[path={0}, catalina.base={1}]",
				new Object[] { webRoot, catalinaBase });
	}

	/**
	 * Destroys the context, unregisters remote JavaScript services.
	 * 
	 * @param servletContextEvent
	 *            servlet context event
	 */
	@Override
	public void contextDestroyed(final ServletContextEvent servletContextEvent) {
	}

	@Override
	public abstract void requestDestroyed(
			final ServletRequestEvent servletRequestEvent);

	@Override
	public abstract void requestInitialized(
			final ServletRequestEvent servletRequestEvent);

	@Override
	public abstract void sessionCreated(final HttpSessionEvent httpSessionEvent);

	@Override
	public abstract void sessionDestroyed(
			final HttpSessionEvent httpSessionEvent);

	/**
	 * Gets the absolute file path of web root directory on the server's file
	 * system.
	 * 
	 * @return the directory file path(tailing with {@link File#separator}).
	 */
	public static String getWebRoot() {
		return webRoot;
	}
}
